<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use app\common\library\FSHelper;

/**
 * 线路管理
 *
 * @icon fa fa-circle-o
 */
class Gateway extends Backend
{
    
    /**
     * Gateway模型对象
     */
    protected $model = null;

    protected $fsHelper = null;
   
    protected $modelValidate = true;

    //protected $dataLimit = 'auth';

    protected $searchFields = 'name,location,username';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Gateway');
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("registerList", $this->model->getRegisterList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    public function selectpage() {
        if (! $this->request->isPost()) {
            $this->error(__('You have no permission'));
        }
        $this->dataLimit = 'auth';

        //return parent::selectpage();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array) $this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr");
        //排序方式
        $orderby = (array) $this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array) $this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array) $this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v)
        {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null)
        {
            $where = [$primarykey => ['in', $primaryvalue]];
        }
        else
        {
            $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
                foreach ($word as $k => $v)
                {
                    foreach ($searchfield as $m => $n)
                    {
                        $query->where($n, "like", "%{$v}%", $andor);
                    }
                }
                if ($custom && is_array($custom))
                {
                    foreach ($custom as $k => $v)
                    {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->where('state', '=', '1')->count();
        if ($total > 0)
        {
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($where)->where('state', '=', '1')
                    ->order($order)
                    ->page($page, $pagesize)
                    ->field("{$primarykey},{$field}")
                    ->field("password,salt", true)
                    ->select();
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['nickname']);
            }
            $list = collection($list)->toArray();

            $this->fsHelper = new FSHelper();
            foreach ($list as &$one) {
                if ($one['state'] != '1') {
                    $one['reg_state'] = '已禁用';
                    continue;
                }
                
                //$one['reg_state'] = ($one['register'] == 'send') ? $this->fsHelper->getGatewayState($one['name']) : $this->fsHelper->getRegState($one['name']);
                $one['reg_state'] = (($one['register'] == 'send') || ($one['register'] == 'none')) ? $this->fsHelper->getGatewayState($one['name']) : $this->fsHelper->getRegState($one['name']);
                if ((strpos($one['reg_state'], 'Registered') !== false)) {
                    $one['reg_state'] = '已注册';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    //if ($params['register'] != 'send') {
                    if (($params['register'] != 'send') && ($params['register'] != 'none')) {
                        $params['register_proxy'] = '';
                        $params['proxy'] = '';;
                        $params['domain'] = '';
                        $params['expires'] = 120;
                    }
                    unset($params['last_call_time']);
                    unset($params['concurrency']);
                    unset($params['concurrency_calls']);

                    $params['username'] = $params['name'];

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->fsHelper = new FSHelper();
                        $params['id'] = $this->model->id;
                        $this->fsHelper->addGateway($params);
                        $this->fsHelper->reloadXML();
                        //if ($params['register'] == 'send') {
                        if (($params['register'] == 'send') || ($params['register'] == 'none')) {
                            $this->fsHelper->rescanGateway('internal');
                        }
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $gatewayValidate = \think\Loader::validate('Gateway');
                        $gatewayValidate->rule([
                            'name' => 'require|max:50|unique:gateway,name,' . $row->id,
                            'username' => 'require|max:50|unique:gateway,username,' . $row->id,
                            //'password' => 'require|max:50',
                        ]);
                        $result = $row->validate('Gateway.edit');
                        if ($result === false)
                        {
                            $this->error($row->getError());
                        }

                        //$name = basename(str_replace('\\', '/', get_class($this->model)));
                        //$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    //if ($params['register'] != 'send') {
                    if (($params['register'] != 'send') && ($params['register'] != 'none')) {
                        $params['register_proxy'] = '';
                        $params['proxy'] = '';;
                        $params['domain'] = '';
                        $params['expires'] = 120;
                    }
                    unset($params['last_call_time']);
                    unset($params['concurrency']);
                    unset($params['concurrency_calls']);

                    $params['username'] = $params['name'];

                    $old_name = $row->name;
                    $old_username = $row->username;
                    $old_register = $row->register;
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->fsHelper = new FSHelper();
                        //if ($old_register = 'send') {
                        if (($old_register = 'send') || ($old_register = 'none')) {
                            $this->fsHelper->killGateway('internal', $old_name);
                        }
                        $this->fsHelper->updateGateway($old_username, $params);
                        //$this->fsHelper->updateIncallDialplanByGateway($old_username, $params);
                        $this->fsHelper->reloadXML();
                        //if ($params['register'] == 'send') {
                        if (($params['register'] == 'send') || ($params['register'] == 'none')) {
                            $this->fsHelper->rescanGateway('internal');
                        }
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            
            $count = 0;

            $this->fsHelper = new FSHelper();
            
            foreach ($list as $k => $v)
            {
                $count += $v->delete();
                $this->fsHelper->delGateway($v->username);
                //if ($v->register == 'send') {
                if (($v->register == 'send') || ($v->register == 'none')) {
                    $this->fsHelper->killGateway('internal', $v->name);
                }
            }
            $this->fsHelper->reloadXML();
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


}
